package titt.io.util.wrap;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import titt.io.socket.in.NuderStream;
import titt.io.socket.out.TITTOutputStream;
import titt.service.content.Mimes;
import titt.util.io.pipe.PipeListener;

public class FileWrapper implements Wrapper {

	private Wrapper ww = new NuderStreamWrapper();

	@Override
	public void writeTo(PipeListener listener, TITTOutputStream out, Object o) throws Exception {
		NuderStream in = convertToStream(o);
		try {
			ww.writeTo(listener, out, in);
		}
		catch(Exception e) {
			in.getInputStream().close();
			throw e;
		}
	}

	@Override
	public boolean supports(Object o) {
		return o instanceof File;
	}

	@Override
	public String getMimeType(Object o) {
		return Mimes.getContentType(((File)o).getName());
	}

	@Override
	public int getLength(Object o) {
		return (int)((File)o).length();
	}

	private NuderStream convertToStream(Object o) {
		try {
			File f = (File)o;
			return new NuderStream(new BufferedInputStream(new FileInputStream(f)), (int)f.length());
		}
		catch(Exception e) {
			return null;
		}
	}

}
